package com.bdqn.mapper;

import com.bdqn.ConfigManager;

import java.sql.*;
import java.util.logging.Logger;

public class BaseDao {

    public static Connection getConnection() {
        Connection connection = null;
        String driver = ConfigManager.getInstance().getValue("driver");
        String url = ConfigManager.getInstance().getValue("url");
        String username = ConfigManager.getInstance().getValue("username");
        String password = ConfigManager.getInstance().getValue("password");
        try {
            Class.forName(driver);
            connection= DriverManager.getConnection(url, username,password);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }
    //对外获取ConfigManager实列的方法
    public static synchronized ConfigManager getInstance(){
        ConfigManager configManager = new ConfigManager();
        //如果configManager不存在就创建一个，存在则直接返回
        if (configManager==null){
            configManager = new ConfigManager();
        }
        return configManager;
    }
    public static void CloAll(ResultSet rs, Statement stmt , Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
               e.printStackTrace();
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public  int executeUpdate(String sql,Object[]param){
        int row=1;
        Connection conn=getConnection();
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            for (int i = 0; i < param.length; i++) {
                pstmt.setObject(i+1,param[i]);
            }
            row= pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            CloAll(null,pstmt,conn);
        }
        return row;
    }
}
